import React, { Component } from 'react';
import { render } from 'react-dom';
import {Link} from 'react-router-dom'
import Messagelist from './messagelist'
require('../public/css/mycss.css');
export class Messageboard extends React.Component{
    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            items:[],
            user:{},
            isEdi:false,
        };
          this.addItem=this.addItem.bind(this);
      }

    componentDidMount() {//----------------------------------获取用户信息
        $.post("/user", {_id: this.props.match.params.id,})
            .then((result) => {
                if(result.status===200)
                {
                    let user=result.user;
                    this.setState({user:user})//存储用户名和id
                }else {
                    // console.log("查询错误！")
                }
                // console.log(result)
            },
            (error) => {
                // console.log(error);
            }
        )
    
    }
    addItem(e){//--------------------------------state存储添加的留言 数据传递给子组件显示，实现页面不刷新更新UI
        let itemArr=this.state.items;
        let msg=this._input.value;
        let id=this.props.match.params.id;
        if(this._input.value!==""){
            $.post("/addmessage",{
                message:this._input.value,
                userId:id,
            }).then((result) => {
                    if(result.status===200)
                    {
                        alert("留言添加成功！");
                        itemArr.push({msg:msg,id:result.msgId});
                        this.setState({
                            items:itemArr,
                        })
                    }else {
                        alert("留言添加失败！")
                    }
                },
                (error) => {
                    // console.log(error);
                }
            )
            this._input.value="  ";
            this._input.focus();
        }else{
            alert("请输入留言信息！");
        }
        e.preventDefault();
    }
    render(){
        let user=this.props.match.params;//----------------路径中存储的用户信息 userName 和 id
        let msglist=`/home/${user.userName}/${user.id}`;
        return <div className="msgIput">
            <h2><Link to={msglist} >留言列表</Link></h2>
            <h3><Link to='/'>退出</Link></h3>
            {this.state.user.images?<img className="userimg" src={`/imgs/${this.state.user.images}.jpg`} alt="" />:null}
            <p>用户名：<strong>{user.userName}</strong></p>
            <p>当前位置：<strong>我的主页</strong></p>
            <form className="head" onSubmit={this.addItem}>
                <input placeholder="说点什么吧" ref={(input)=>this._input=input}/>
                <button >留言</button>
            </form>
            <Messagelist type={1} source={`/getmessage/${user.id}`}  items={this.state.items} myname={user.userName} images={this.state.user.images}/>
        </div>
    }
}